from rest_framework import serializers

from goods.models import SKU


class CartSerializers(serializers.Serializer):
    sku_id = serializers.IntegerField(min_value=1, label="商品编号")
    count = serializers.IntegerField(min_value=1, max_value=200, label="数量")
    selected = serializers.BooleanField(default=True, required=False)


    # 1,多字段校验
    def validate(self, attrs):
        # 0,获取数据
        sku_id = attrs["sku_id"]
        count = attrs["count"]

        # 1,判断商品是否存在
        try:
            sku = SKU.objects.get(id=sku_id)
        except Exception as e:
            raise serializers.ValidationError("商品不存在")

        # 2,判断count是否大于了库存量
        if count > sku.stock:
            raise serializers.ValidationError("库存不足")

        # 3,返回
        return attrs